define(function(require, exports){
	var $ = require("jquery");
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var util = require('util');
	var common = require('modules/common');

	var Linked = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'class': 'M-linked',
				'value': '',			// 按钮显示名称
				'tips': '',				// 说明提示
				'popwin': {				// 弹框配置
					uri: '',
					param: {
						autoShow: true,
						silence: false
					}
				},
				'box': {				// 子元素配置
					uri: 'modules/linked.box'
				}
			});

			this.$data = [];
			this.$popwinData = {};
			this.Super('init', arguments);
		},
		afterBuild:function(){
			var c = this.getConfig();

			this.append([
				'<div class="M-linkedContainer">',
				'</div>',
				'<span pub-mod="@base/common/input.button" pub-name="add" />',
				c.tips ? '<span class="ml10" pub-name="tips" pub-mod="@base/tip.desc" />': ''

			].join(''));

			var config = {
				add: {
					'width': 0,
					'value': c.value,
					'class': 'btn btn-default'
				},
				tips: {
					'width': 300,
					'data': c.tips
				}
			};

			this.buildFromTemplate(config);
		},
		onInputClick: function(ev){
			if(ev.name == 'add'){
				this.showPopwin();
			}
		},
		showPopwin: function(){
			var popwin = this.getConfig('popwin');

			var mod = this.get('popwin');
			if(!mod){
				this.createAsync('popwin', popwin.uri, popwin.param, function(mod){
					mod.setValue(this.$popwinData);
				});
			}else{
				mod.reload().show();
			}
		},
		onSelectProductOk: function(ev){
			if(ev.name === 'popwin')
			{
				var popwin = this.$.popwin;
				var data = popwin.getValue();
				popwin.hide();

				this.setData(data);
				return false;
			}
		},
		setData: function(data){
			var self = this
				,index;
			for(var item in data){
				if(data.hasOwnProperty(item)){
					index = self.$data.indexOf(+item);
					if(index == -1){
						self.$data.push(+item);
						this.buildItem(data[item]);
					}
				}
			}
		},
		onRemoveItem: function(ev){
			var self = this;
			var id = +ev.param.id;
			var index = self.$data.indexOf(+id);
			if(index > -1){
				self.$data.splice(index, 1);
				self.$['sub_'+ id].destroy();
			}
		},
		buildItem: function(data){
			var box = this.getConfig('box');
			this.createAsync('sub_'+data._id, box.uri, util.extend({
				target: this.$el.find('.M-linkedContainer'),
				data: data
			},box.param));
		},
		onChildDestroy: function(ev){
			var id = +ev.param._id;
			var index = this.$data.indexOf(id);
			if(index == -1){
				return false;
			}
			var pop = this.$.popwin;
			this.send(pop, 'removeItem', {id: id});

			this.$data.splice(index, 1);
			// 删除传给弹窗的对应的值
			delete this.$popwinData[id];

			return false;
		},
		getValue: function(){
			return this.$data;
		},
		setValue: function(data){
			this.$popwinData = {};
			if( !util.isArray(data) ){
				data = [data];
			}
			for (var i = 0; i < data.length; i++) {
				var item = data[i];
				this.$data.push(+item._id);
				this.buildItem(item);
				// 编辑时，用来摄者弹窗表格的值
				this.$popwinData[item._id] = item;
			}
		},
		reset: function(){
			this.$data = [];
			this.$popwinData = [];

			// 销毁子模块
			for (var e in this.$) {
				if(e.match('sub_')){
					this.$[e].destroy();
				}
			}
		}
	});
	exports.base = Linked;

	// 子项目
	var LinkedBox = view.container.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'class': 'M-linkedBox',
				'titleField': 'title',
				'imgField': 'img',
				'title': '',
				'data': null
			});
			this.Super('init', arguments);
		},
		afterBuild: function(){
			var c = this.getConfig();
			var data = c.data;
			var title = c.title || data[c.titleField];
			var url = data.Cover.thumb + '&w=65&h=65';
			this.append($([
				'<div class="delete" />',
				'<div class="image"><img src="'+url+'" / ></div>',
				'<div class="title uk-text-truncate" title="'+title+'">'+title+'</div>'
			].join('')));

			var img = this.find('img');
			common.loadImage('default', url, img);

			var config = {
				'delete': {
					value: ''
				}
			};

			this.uiBind(this.$el.find('.delete'), 'click', 'eventRemove');

			this.buildFromTemplate(config);
		},
		eventRemove: function(ev){
			this.fire('childDestroy', this.getConfig('data'), 'afterChildDestroy',  this);
			return false;
		},
		afterChildDestroy: function(ev){
			this.destroy();
		}
	});
	exports.box = LinkedBox;

	//产品
	var ProductBox = LinkedBox.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'titleField': 'Name',
				'imgField': 'Cover'
			});
			this.Super('init', arguments);
		},
		afterBuild: function(){
			var c = this.getConfig();
			c.title = c.data[c.titleField].substr( 0, c.data[c.titleField].lastIndexOf('_'));
			this.Super('afterBuild', arguments);
		}
	});
	exports.productBox = ProductBox;

});